import Vue from "vue";
import VueRouter from "vue-router";
import layout from "../pages/layout/layout.vue";
import UserTokenModule from "@/tools/token"
import ErrorPage from "../pages/error/404.vue";
// import { getToken } from "@/assets/overall/js/module/token";
import config from "@/config";

import RouterViewMenusModule from "@/tools/vital/menus_data"

// import { get as GetSessionMenusData } from "@/assets/overall/js/module/sessionStorage";
import formatModule from "@/tools/format";
// import AdminStore from '@/store'
import SystemConfig from "@/config";
const { systemInfo } = SystemConfig;
const SystemStoreModuleName = systemInfo.StoreModuleName;
/**
 *  @name 解决Vue-router 函数式编程重复点击导航控制台报错
 *  @url https://blog.csdn.net/luer_LJS/article/details/108362563?spm=1001.2101.3001.6650.13&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-13-108362563-blog-123013967.pc_relevant_3mothn_strategy_recovery&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7ERate-13-108362563-blog-123013967.pc_relevant_3mothn_strategy_recovery&utm_relevant_index=14
 *
 **/
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};
Vue.use(VueRouter);
const router = new VueRouter({
  mode: "hash",
  routes: [
    {
      name: "layout",
      path: "/",
      component: layout,
      children: [],
    },
    {
      name: "login",
      path: "/login",
      component: () => import("../pages/login"),
    },
    {
      name: "403",
      path: "/403",
      component: () => import("../pages/error/403"),
    },
    {
      name: "404",
      path: "/404",
      component: ErrorPage,
    },
    {
      path: "*",
      component: () => import("../pages/error/404"),
    },
  ],
});
// 路由全局前置守卫
router.beforeEach(function (to, form, next) {
  router.app.$store.commit(
    `${SystemStoreModuleName}/SET_ROUTER_TO_INFO`,
    to
  );
  router.app.$store.commit(
    `${SystemStoreModuleName}/SET_ROUTER_FORM_INFO`,
    form
  );
    // 设置路由框为加载状态
  router.app.$store.commit(
    `${SystemStoreModuleName}/SET_ROUTERVIEW_LOADING`,
    true
  );

  // 跳转携带的Query参数
  let toQuery = to.query
  // 跳转携带的Props
  let toProps = to.params
  // 登陆页面路径
  let loginPath = "/login";
  // 用户Token
  let UserToken = UserTokenModule.getUserToken()
  // 是否为登录页面
  let currentPageIfLoginPath = to.path == loginPath
  //   如果访问的是登录页面，直接放行
  if (currentPageIfLoginPath) {
    next();
  } else {
    // 没有用户token
    if (!UserToken) {
      let formPath = form.path
      if (formPath != loginPath) {
        next(loginPath);
      } else {
        console.log("无用户Token");
      }
    } else {
      // 获取VueX 
      let Vuex = router.app.$store
      // 获取VueX 以及本地缓存的VueRouter路由信息
      let OriginMenusData = []
      // VueX中存储的路由源数组
      let RouterOriginList = Vuex.getters[`${SystemStoreModuleName}/GetRouterOriginList`]
      if (!RouterOriginList.length) {
        // 获取本地存储的路由信息
        let getStorageMenusList = RouterViewMenusModule.GetMenusList()
        // 本地存储的源数组没有数据
        if (!getStorageMenusList || !getStorageMenusList.length) {
          next(loginPath);
          return
        } else {
          OriginMenusData = getStorageMenusList
        }
        // 将路由信息格式化
        let ArrayFormatVueRouter = formatModule.ArrayFormatVueRouter(
          OriginMenusData
        );
        // 将格式化后的数组动态添加到VueRouter
        ArrayFormatVueRouter.forEach((item) => {
          router.addRoute("layout", item);
        });
        // 将扁平的菜单数据更新到VueX
        router.app.$store.commit(
          `${SystemStoreModuleName}/SetRouterOriginList`,
          OriginMenusData
        );


        // 放行页面
        next({
          path: to.path,
          query: toQuery,
          params: toProps
        });
      } else {
        next()
      }
      // 取消路由加载框加载状态
      router.app.$store.commit(
        `${SystemStoreModuleName}/SET_ROUTERVIEW_LOADING`,
        false
      );

    }
  }
 
});
// 路由全局后置守卫
router.afterEach((to) => {
  let id = to.meta.id
  // 将当前页面的ID存入到VueXw
  router.app.$store.commit(
    `${SystemStoreModuleName}/ENTER_ROUTER`,
    { id }
  );
  let title = config.systemInfo.title
  document.title = title
})

// 路由错误守卫
router.onError((error, data) => {

  // 取出当前错误的路由route对象
  let route = router.currentRoute
  console.log("currentRoute",route);

  console.log("路由跳转错误", error, data);
})
export default router;
